﻿using Anke.SHManage.IDAL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Anke.SHManage.Model.BasicEventInfo;
using System.Reflection;

namespace Anke.SHManage.MSSQLDAL
{
    public class AlarmEventDAL : IAlarmEventDAL 
    //: IAlarmEventDAL
    {
        public AlarmEventInfo GetAlarmEventInfoByCode(string EventCode)
        {
            AlarmEventInfo aeInfo = new AlarmEventInfo();
            StringBuilder strSQL = new StringBuilder();
            strSQL.Append(@"
SELECT 事件编码,首次呼救电话,首次受理时刻,事件名称
    ,TZEO.名称 as 事件来源,TZET.名称 as 事件类型,TZAT.名称 as 事故类型,TZAL.名称 as 事故等级
    ,TAE.是否测试,受理次数,撤消受理数,执行任务总数,当前执行任务数,中止任务数  
    ,首次调度员编码,首次调度员工号=tp.工号,TP.姓名 as 首次调度员
    ,挂起时刻,预约时刻,首次派车时刻,是否挂起,是否标注,X坐标,Y坐标,区域
    ,占用台号,TAE.中心编码,中心名称=tc.名称,表单完成标志,TAE.病情编码,病情=TZI.名称
    ,是否落单 ,事件来源编码,事故等级编码,事故类型编码  
FROM TAlarmEvent TAE 
left join TZAlarmEventType TZET on TZET.编码 = TAE.事件类型编码
left join TZAlarmEventOrigin TZEO on TZEO.编码 =TAE.事件来源编码
left join TZAccidentType TZAT on TZAT.编码 = TAE.事故类型编码
left join TZAccidentLevel TZAL on TZAL.编码 =TAE.事故等级编码
left join TZIllState TZI on TZI.编码 =TAE.病情编码
left join TPerson TP on TP.编码=TAE.首次调度员编码
left join TCenter tc on tc.编码=TAE.中心编码
where tae.事件编码 = '" + EventCode + @"'");
            using (SqlDataReader sdr = SqlHelper.ExecuteReader(SqlHelper.AttemperConnectionString, CommandType.Text, strSQL.ToString(), null))
            {
                if (sdr.Read())
                {
                    aeInfo.EventCode = sdr["事件编码"].ToString();
                    aeInfo.FirstAlarmCall = sdr["首次呼救电话"].ToString();
                    aeInfo.EvetnName = sdr["事件名称"].ToString();
                    aeInfo.EventType = sdr["事件类型"].ToString();
                    aeInfo.EventSource = sdr["事件来源"].ToString();
                    aeInfo.AccidentType = sdr["事故类型"].ToString();
                    aeInfo.AccidentLevel = sdr["事故等级"].ToString();
                    aeInfo.IsTest = Convert.ToBoolean(sdr["是否测试"]);
                    aeInfo.AcceptCount = Convert.ToInt32(sdr["受理次数"]);
                    aeInfo.CancelAcceptCount = Convert.ToInt32(sdr["撤消受理数"]);
                    aeInfo.TransactTaskCount = Convert.ToInt32(sdr["执行任务总数"]);
                    aeInfo.NonceTransactTaskCount = Convert.ToInt32(sdr["当前执行任务数"]);
                    aeInfo.BreakTaskCount = Convert.ToInt32(sdr["中止任务数"]);

                    aeInfo.FirstDisptcherName = sdr["首次调度员"].ToString();
                    aeInfo.FirstDisptcherWorkID = sdr["首次调度员工号"].ToString();//2013.04.11 刘爱青 add
                    aeInfo.FirstAcceptTime = DBConvert.ConvertNullableToNullableTime(sdr["首次受理时刻"].ToString());
                    aeInfo.HangUpTime = DBConvert.ConvertNullableToNullableTime(sdr["挂起时刻"].ToString());
                    aeInfo.BespeakTime= DBConvert.ConvertNullableToNullableTime(sdr["预约时刻"].ToString());
                    aeInfo.FirstSendAmbTime = DBConvert.ConvertNullableToNullableTime(sdr["首次派车时刻"].ToString());
                    aeInfo.IsHangUp = Convert.ToBoolean(sdr["是否挂起"]);
                    aeInfo.IsLabel = Convert.ToBoolean(sdr["是否标注"]);
                    aeInfo.X = Convert.ToDouble(sdr["X坐标"]);
                    aeInfo.Y = Convert.ToDouble(sdr["Y坐标"]);
                    aeInfo.Area = sdr["区域"].ToString();
                    aeInfo.TieUpDeskCode = sdr["占用台号"].ToString();
                    aeInfo.CenterCode = Convert.ToInt32(sdr["中心编码"]);
                    aeInfo.CenterName = sdr["中心名称"].ToString();
                    aeInfo.IsFinish = Convert.ToBoolean(sdr["表单完成标志"]);
                    aeInfo.IllStateName = sdr["病情"].ToString();
                    aeInfo.IsPlaceOrder = Convert.ToBoolean(sdr["是否落单"]);
                    //增加“事件来源编码”、“事故等级编码”、“事故类型编码”三个字段 2016-10-27
                    aeInfo.EventSourceCode = Convert.ToInt32(sdr["事件来源编码"]);
                    aeInfo.AccidentLevelCode = Convert.ToInt32(sdr["事故等级编码"]);
                    aeInfo.AccidentTypeCode = Convert.ToInt32(sdr["事故类型编码"]);
                }
            }
            return aeInfo;
        }

        //获取事件电话录音
        public object GetAlarmCalls(int page, int rows,ref int rowtotal, string eventCode, int OrderNumber)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select 
                         identity(int,1,1) as 行号, 
                        ac.通话时刻,ac.结束时刻,ac.台号,d.显示名称,ac.调度员编码, p.姓名,p.工号
                         ,ct.名称,ac.事件编码,ac.主叫号码,ac.录音号,ac.是否呼出 

                        into #temp
	                    from TAlarmCall   ac 
	                    left join TZAcceptEventType ct on  ac.通话类型编码 = ct.编码 
	                    left join TPerson p on p.编码 = ac.调度员编码 
	                    left join TDesk d on ac.台号= d.台号

	                     where ac.事件编码='" + eventCode + @"'  and ct.是否有效 = 1    ");

            sb.Append(@"select top " + rows + " A.*  from #temp A where 行号>" + (page - 1) * rows + " order by 行号 ");
            sb.Append(@"SELECT count(*) FROM #temp t ");
            sb.Append("drop table #temp ");
            
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);

            List<AlarmCallInfo> list = new List<AlarmCallInfo>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                AlarmCallInfo info = new AlarmCallInfo();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new AlarmCallInfo();
                    info.CallTime = Convert.ToDateTime(dr["通话时刻"]);
                    info.EndCallTime = Convert.ToDateTime(dr["结束时刻"]);
                    info.TeskCode = dr["显示名称"].ToString();
                    info.DispatcherName = Convert.ToString(dr["姓名"]);
                    info.DispatcherWorkCode = dr["工号"].ToString();
                    info.CallType = Convert.ToString(dr["名称"]);
                    info.EventCode = dr["事件编码"].ToString();
                    //info.OrderNumber = dr["受理序号"].ToString();
                    info.CallNumber = dr["主叫号码"].ToString();
                    info.RecordNumber = dr["录音号"].ToString();
                    info.IfCallOut = Convert.ToBoolean(dr["是否呼出"]);
                    list.Add(info);
                }
            }
            else
            {
                list = null;
             
                rowtotal = 0;
                return list;
            }
            int total = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            rowtotal = total;
           
            return list;
        }

        
        /// <summary>
        /// 根据工号查询人员信息
        /// </summary>
        /// <param name="workID"></param>
        /// <returns></returns>
        public PersonInfo GetPreson(string workID)
        {
            DataBase db = new DataBase(SqlHelper.AttemperConnectionString);
            PersonInfo info = (from a in db.PersonInfo
                               where a.JobCode == workID
                               select a).FirstOrDefault();
            return info;
        }


        #region 保存修改事件信息 2016-10-26
        public bool UpdateEvent(string EventCode, string EvetnName, string Area, int EventSourceCode, int AccidentLevelCode, int AccidentTypeCode)
        {
            try
            {
                StringBuilder strSQL = new StringBuilder();
 
                strSQL.Append(@"update TAlarmEvent set 区域='" + Area + "',事件来源编码='" + EventSourceCode + "', 事故等级编码='" + AccidentLevelCode + "',事故类型编码='" + AccidentTypeCode + "',事件名称='" + EvetnName + "'");
                strSQL.Append(@" where 事件编码='" + EventCode + "'");

                int ds = SqlHelper.ExecuteNonQuery(SqlHelper.AttemperConnectionString, CommandType.Text, strSQL.ToString(), null);
                return ds > 0 ? true : false;
            }
            catch (Exception ex)
            {
                LogUtility.Error("AlarmEventDAL/UpdateEvent()", ex.ToString());
                return false;
            }
        }

        private static Dictionary<string, int> m_ModifyEventTypeDic = null;
        public string ModifyEvent(AlarmEventInfo info, string operatorCode)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(SqlHelper.AttemperConnectionString))
                {

                    DataBase db = new DataBase(con);
                    AlarmEventInfo originInfo = (from aei in db.AlarmEventInfo
                                                  where aei.EventCode == info.EventCode
                                                  select aei).FirstOrDefault();
                    if (originInfo == null)
                        return "没有找到对应的任务实体";

                    #region 更新主表
                    m_ModifyEventTypeDic = new Dictionary<string, int>();
                    m_ModifyEventTypeDic.Add("EvetnName", 121);//事件名称
                    m_ModifyEventTypeDic.Add("Area", 28);//区域
                    m_ModifyEventTypeDic.Add("EventSourceCode", 0);//事件来源编码
                    m_ModifyEventTypeDic.Add("AccidentLevelCode", 3);//事故等级编码
                    m_ModifyEventTypeDic.Add("AccidentTypeCode", 1);//事故类型编码

                    List<ModifyRecordInfo> mriList = new List<ModifyRecordInfo>();
                    //获得所有property的信息
                    PropertyInfo[] properties = originInfo.GetType().GetProperties();
                    foreach (PropertyInfo p in properties)
                    {
                        int typeId = -1;
                        if (m_ModifyEventTypeDic.TryGetValue(p.Name, out typeId)) //如果需要修改
                        {
                            object oldObj = p.GetValue(originInfo, null);
                            object newObj = p.GetValue(info, null);
                            string oldValue = oldObj == null ? "" : oldObj.ToString();
                            string newValue = newObj == null ? "" : newObj.ToString();
                            if (!object.Equals(oldValue, newValue))
                            {
                                p.SetValue(originInfo, newObj, null);
                                ModifyRecordInfo mri = new ModifyRecordInfo();
                                mri.Code = Guid.NewGuid();
                                mri.NewContent = newObj.ToString();//2011-02-14 如果是null就费了。
                                mri.OriginContent = oldObj.ToString();//2011-02-14 如果是null就费了。
                                mri.OperateTime = DateTime.Now;
                                mri.OperatorCode = operatorCode;
                                mri.TypeId = typeId;
                                mri.EventCode = originInfo.EventCode;
                                //mri.AcceptOrder = oldObj.ToString();
                                //mri.TaskCode = originInfo.TaskCode();//任务编码
                                mriList.Add(mri);
                            }
                        }
                    }
                    db.ModifyRecordInfos.InsertAllOnSubmit(mriList);
                    #endregion
                    db.SubmitChanges();
                    return "";
                }
            }
            catch (Exception ex)
            { return ex.ToString(); }
        }

        /// <summary>
        /// 查询事件修改痕迹
        /// 20161025 周志猛 add
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowCount"></param>
        /// <param name="EventCode"></param>
        /// <returns></returns>
        public List<ModifyRecordInfo> GetEventCrackInfos(int pageIndex, int pageSize, ref int rowCount, string EventCode)
        {
            DataBase db = new DataBase(SqlHelper.AttemperConnectionString);

            var qry = (from alm in db.ModifyRecordInfos
                       join m in db.ModifyRecordTypeInfo on alm.TypeId equals m.BianMa into temp
                       join person in db.PersonInfo on alm.OperatorCode equals person.Code into tempPerson
                       from tt in temp.DefaultIfEmpty()
                       from p in tempPerson.DefaultIfEmpty()
                       where alm.EventCode == EventCode & alm.AcceptOrder==null
                       select new
                       {
                           Code = alm.Code,
                           EventCode = alm.EventCode,
                           OperatorName = p == null ? "" : p.Name,//这里主要第二个集合有可能为空。需要判断
                           OperateTime = alm.OperateTime,
                           StringOperateTime = alm.OperateTime.ToString(),
                           TypeName = tt == null ? "" : tt.MingCheng,//这里主要第二个集合有可能为空。需要判断
                           OriginContent = alm.OriginContent,
                           NewContent = alm.NewContent
                       }).ToList();
            List<ModifyRecordInfo> list = new List<ModifyRecordInfo>();
            ModifyRecordInfo info = new ModifyRecordInfo();
            for (int i = 0; i < qry.Count; i++)
            {
                info = new ModifyRecordInfo();
                info.Code = (Guid)qry[i].Code;
                info.EventCode = qry[i].EventCode.ToString();
                info.OperatorName = qry[i].OperatorName.ToString();
                info.OperateTime = Convert.ToDateTime(qry[i].OperateTime);
                info.StringOperateTime = Convert.ToDateTime(qry[i].StringOperateTime).ToString("yyyy-MM-dd HH:mm:ss");
                info.TypeName = qry[i].TypeName.ToString();
                info.OriginContent = qry[i].OriginContent.ToString();
                info.NewContent = qry[i].NewContent.ToString();
                list.Add(info);
            }
            list = list.OrderByDescending(t => t.OperateTime).ToList();
            rowCount = qry.Count;
            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }
        #endregion
    }
}
        